package com.mobilesales.android.activities.tasks;

import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

import com.mobilesales.android.R;
import com.mobilesales.android.activities.ListModelActivity;
import com.mobilesales.android.adapters.SlidingMenus;
import com.mobilesales.android.adapters.TaskAdapter;
import com.mobilesales.android.database.TaskManager;
import com.mobilesales.android.infrastructure.SyncItemTask;
import com.mobilesales.android.model.tasks.CyclicTask;
import com.mobilesales.android.model.tasks.Schedule;
import com.mobilesales.android.model.tasks.Task;
import com.mobilesales.android.util.Constants;
import com.mobilesales.android.util.DateUtil;
import com.mobilesales.android.util.MessageBox;
import com.mobilesales.android.util.SelectDateTime;
import com.mobilesales.android.util.Settings;

public class ListTask extends ListModelActivity<Task> {

	private TextView currentDateField;
	private TextView currentMonthShortField;
	private Button mapBtn;

	private List<Task> tasksOfDay;
	private Date selectedDate;
	private TaskAdapter itemsAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.task_list);
		new SlidingMenus(this);
		currentDateField = (TextView) this.findViewById(R.id.currentDate);
		currentMonthShortField = (TextView) this
				.findViewById(R.id.currentMonthShort);
		mapBtn = (Button) this.findViewById(R.id.mapBtn);

		Bundle bundle = this.getIntent().getExtras();
		if (bundle != null && bundle.containsKey(Constants.SelectedDate)) {
			selectedDate = (Date) bundle.get(Constants.SelectedDate);
			Log.i("selectedDate", selectedDate.toLocaleString());
			currentDateField.setText(String.valueOf(selectedDate.getDate()));
			int[] monthNameResIds = DateUtil.monthNamesStringResourceIds();
			String monthName = getString(monthNameResIds[selectedDate
					.getMonth()]);
			currentMonthShortField.setText(monthName.substring(0, 3));

			loadItems();
		} else {
			MessageBox.show(this, getString(R.string.ErrorTaskList));
			finish();
		}
	}

	private void loadItems() {
		tasksOfDay = this.getItems();
		if (tasksOfDay != null) {
			if (tasksOfDay.size() > 0)
				mapBtn.setEnabled(true);
			this.setItemsSource(tasksOfDay);
		} else {
			MessageBox.show(this, getString(R.string.ErrorTaskList));
			finish();
		}
	}

	@Override
	protected void onListItemClick(ListView listView, View view, int position,
			long id) {
		super.onListItemClick(listView, view, position, id);
		Task task = itemsAdapter.getItem(position);
		boolean isCyclicTask = (task instanceof CyclicTask);
		Intent intent = new Intent(this, DetailsTask.class);
		intent.putExtra(Constants.TaskId, task.Id);
		intent.putExtra(Constants.IsCyclicTask, isCyclicTask);
		this.startActivityForResult(intent, 0);
	}

	private List<CyclicTask> getCyclicTasks(Date currentDate) {
		Log.i("currentDate", currentDate.toLocaleString());
		TaskManager manager = new TaskManager(this);
		List<CyclicTask> tasks = manager.GetCyclicTaskList(Settings
				.getSettings().getEmployeeId());
		manager.Close();

		SelectDateTime selectdate = new SelectDateTime(this);
		List<CyclicTask> taskInTime = null;
		if (tasks != null) {
			taskInTime = new ArrayList<CyclicTask>();
			GregorianCalendar calendar = new GregorianCalendar();
			for (CyclicTask tsk : tasks) {
				Date date = selectdate.getDate(tsk.StartTime);
				calendar.setTime(date);
				GregorianCalendar current = new GregorianCalendar();
				current.setTime(currentDate);
				current.set(GregorianCalendar.HOUR_OF_DAY,
						calendar.get(GregorianCalendar.HOUR_OF_DAY));
				current.set(GregorianCalendar.MINUTE,
						calendar.get(GregorianCalendar.MINUTE));

				Log.i("Current", current.getTime().toLocaleString());
				Log.i("Day", calendar.getTime().toLocaleString());

				long diff = current.getTimeInMillis()
						- calendar.getTimeInMillis();
				Log.i("diff", diff + "");
				Log.i("taskInterval", tsk.TaskInterval + "");
				Log.i("diff % tsk.TaskInterval", (diff % tsk.TaskInterval) + "");
				if (diff >= 0) {
					diff /= (24 * 60 * 60 * 1000);
					if (tsk.TaskInterval != 0 && diff % tsk.TaskInterval == 0)
						taskInTime.add(tsk);
				}
			}
			Log.i("MobileSales", "taskInTime:" + taskInTime.size());
		}
		return taskInTime;
	}

	/**
	 * Get list task from SQLite
	 * 
	 * @param date
	 * @return
	 */
	private List<Task> getTasks(Date date) {
		List<Task> tasks = null;
		TaskManager manager = new TaskManager(this);
		List<Schedule> schedules = manager.GetScheduleList(Settings
				.getSettings().getEmployeeId());
		// get all Task
		if (schedules != null) {
			tasks = new ArrayList<Task>();
			for (Schedule s : schedules) {
				List<Task> stasks = manager.GetTaskList(s.Id);
				if (stasks != null) {
					tasks.addAll(stasks);
				} else {
					tasks = null;
					break;
				}
			}
		}
		manager.Close();
		//
		SelectDateTime selectDate = new SelectDateTime(this);
		if (tasks != null) {
			List<Task> incorrect = new ArrayList<Task>();
			for (Task t : tasks) {
				// so sanh 2 ngay
				String currentDate = selectDate.FormatDate(date);
				String taskDate = selectDate.FormatDate(t.StartTime);
				if (!currentDate.equals(taskDate)) {
					incorrect.add(t);
				}
			}
			for (Task t : incorrect)
				tasks.remove(t);
		}
		return tasks;
	}

	public void addTask(View v) {
		Intent intent = new Intent(this, StoreTask.class);
		intent.putExtra(Constants.IsCyclicTask, false);
		intent.putExtra(Constants.SelectedDate, this.selectedDate);
		this.startActivityForResult(intent, 0);
	}

	public void showMap(View v) {
		Intent intent = new Intent(v.getContext(), TaskMaps.class);
		intent.putExtra(Constants.SelectedDate, selectedDate);
		startActivityForResult(intent, 0);
	}

	public void addCyclicTask(View v) {
		Intent intent = new Intent(this, StoreTask.class);
		intent.putExtra(Constants.IsCyclicTask, true);
		intent.putExtra(Constants.SelectedDate, this.selectedDate);
		this.startActivityForResult(intent, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			SyncItemTask sync = new SyncItemTask(this, 1);
			sync.execute();
		}
		this.loadItems();
	}

	public void finish(View v) {
		finish();
	}

	public void refresh() {
		getHandler().post(new Runnable() {
			public void run() {
				loadItems();
			}
		});
	}

	@Override
	protected void setItemsSource(List<Task> source) {
		itemsAdapter = new TaskAdapter(this, R.layout.task_list_item, source);
		this.setListAdapter(itemsAdapter);
	}

	@Override
	protected List<Task> getItems() {
		if (this.selectedDate != null) {
			List<Task> tasks = getTasks(selectedDate);
			List<CyclicTask> cyclicTasks = getCyclicTasks(selectedDate);
			List<Task> tasksOfDay = new ArrayList<Task>();
			if (tasks != null && cyclicTasks != null) {
				for (Task tsk : tasks)
					tasksOfDay.add(tsk);
				for (CyclicTask tsk : cyclicTasks)
					tasksOfDay.add(tsk);
				return tasksOfDay;
			}
		}
		return null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater menuInflater = new MenuInflater(this);
		menuInflater.inflate(R.menu.task_list_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		int i = item.getItemId();
		switch (i) {
		case R.id.menu_task_list_AddTask:
			addTask(null);
			break;
		case R.id.menu_task_list_AddCyclicTask:
			addCyclicTask(null);
			break;
		default:
			break;
		}
		return true;
	}
}
